// pages/contest/contest.js
let app = getApp();
let bluetoothtool = require("../../utils/bluetoothtool.js");
let httptool = require("../../utils/zry.httptool.js");
let tabjs = require("../../utils/tab.js");

Page({
  data:{
    deviceId: '',
    statuses:[0,0,0,0,0,0,0],
    bgCover:true,
    shareArea:true,
    activeIndex:'1',
    msgprop:'',//消息提示  
  },
  currentScore:function(e){//查看当前局成绩
    wx.navigateTo({
      url: '/pages/contestscore/contestscore?shareType=' + 2
    })
  },
  checkRule:function(e){//查看规则
    wx.navigateTo({
      url: '/pages/daleiRule/leirule',
    })
  },
  onLoad: function (options) {
    let self=this;
    this.onBLECharacteristicValueChange();   
     
    if (options.deviceId) {
      wx.setStorageSync("deviceId", options.deviceId);
      wx.setStorageSync("deviceName", options.deviceName); 
      wx.setStorageSync("boxStatus", "选择模式");
      this.setData({ deviceId: options.deviceId }); 
    }
    let statuses = wx.getStorageSync("statuses");
    self.setStatuses(self, statuses);        
  },
  selectModel:function(e){
    let self = this;
    let index = e.currentTarget.dataset.index;
    let value = e.currentTarget.dataset.value; 
    let statuses = self.data.statuses;
    statuses[index] = value == 0 ? 1 : 0;
    if ((statuses[0] == 1 && statuses[1] == 1) ||
      (statuses[0] == 1 && statuses[2] == 1) ||
      (statuses[1] == 1 && statuses[2] == 1)) {
      statuses[6] = 1;
    }else{
      statuses[6]=0;
    }
    self.setData({ statuses: statuses });
  },
  beginGo:function(){
    let self=this;
    if (this.data.statuses[6] == 1) {
      let UserId = app.getStorage('customerId');
      httptool.ajaxPost("api/BoxRecord/IsForceShare", { UserId: UserId }, function (res) {
        if(res.suc){
          if (!res.data){
            let deviceId = wx.getStorageSync("deviceId");
            let serviceId = wx.getStorageSync("serviceId");
            let uuid = wx.getStorageSync("uuid"); 
            let hex = self.getSendValue();
            //上传靶位
            console.log("发送的16进制命令为：" + hex);
            bluetoothtool.writeBLECharacteristicValue(deviceId, serviceId, uuid, hex);
            wx.setStorageSync("boxStatus", "打擂中");
            wx.setStorageSync("boxQty", self.getBoxQty());
            wx.redirectTo({
              url: '/pages/contesting/contesting'
            });
          } else {
            self.setData({ shareArea: false, bgCover: false });
          }          
        }    
      });      
    }else{
      app.showNotify(self, "主靶组合必选");
    }
  },
  getSendValue(){
    let statuses = this.data.statuses;
    let hex="";
    let sendhex="";
    for (let i in statuses){
      if(i<6){
        if (statuses[i] == -1) {
          hex = "0" + hex;
        } else {
          hex = statuses[i] + hex;
        }
      }      
    }
    let boxlet = parseInt(hex, 2); 
    console.log("boxlet=" + boxlet);
    if (boxlet > 15){
      sendhex = "405323" + boxlet.toString(16) + "2340";
    }else{
      sendhex = "4053230" + boxlet.toString(16) + "2340";
    }    
    
    return sendhex;
  },
  getBoxQty(){
    let qty=1;
    let statuses = this.data.statuses;
    for (let i in statuses) {
      if (i>2&&i < 6) {
        if (statuses[i] == 1) {
          qty++
        } 
      }
    }

    return qty;
  },
  onBLECharacteristicValueChange:function(){
    let self = this; 
    wx.onBLECharacteristicValueChange(function (res) {
      let backresult = bluetoothtool.decodeUtf8(res.value);
      if (backresult)
        backresult = backresult.toUpperCase();
      console.log('backresult=' + backresult);
      if (/^#[0-9]+$/.test(backresult)) {//收到靶位信息，并提示配对成功，发送字符串：ACK#OK#
        self.setStatuses(self, backresult);        
        let deviceId = wx.getStorageSync("deviceId");
        let serviceId = wx.getStorageSync("serviceId");
        let uuid = wx.getStorageSync("uuid");
        bluetoothtool.writeBLECharacteristicValue(deviceId, serviceId, uuid, "41434b234f4b23");//ACK#OK#
      }else if (backresult.indexOf("#R#") == 0){//收到成绩
        self.recieveScore(backresult);
      }
      else if (backresult=="#ACKTION#"){
        let url = app.getCurrentPageUrl();
        wx.setStorageSync("boxStatus", "打擂中");
        if (url == "pages/contestscore/contestscore" || url == "pages/contest/contest") {
          wx.redirectTo({
            url: '/pages/contesting/contesting'
          });
        }
      } else if (backresult == "#RESET#"){
        wx.removeStorageSync("deviceId");
        wx.removeStorageSync("deviceName");
        wx.removeStorageSync("boxStatus");
        app.showNotify(self, "请注意，手机蓝牙与设备断开连接！",function(){
          wx.redirectTo({
            url: '/pages/startBluetooth/startBlue'
          });
        });
      }
    });
  }, 
  recieveScore: function (backresult){    
    let param = {};
    param.UserId = wx.getStorageSync("customerId");
    param.BoxQty = wx.getStorageSync("boxQty");
    param.BeatEnemy = backresult.replace("#R#", "").replace("#", "");
    httptool.ajaxPost("api/BoxRecord/AddBoxRecords", param, function () {
      let UserId = app.getStorage('customerId');
      wx.setStorageSync("boxStatus", "查看成绩");
      httptool.ajaxPost("api/BoxRecord/IsForceShare", { UserId: UserId }, function (res) {
        if (res.suc) {
          let deviceId = wx.getStorageSync("deviceId");
          let serviceId = wx.getStorageSync("serviceId");
          let uuid = wx.getStorageSync("uuid");
          if (res.data) {
            //发送强制分享命令@stop
            console.log("强制分享")
            bluetoothtool.writeBLECharacteristicValue(deviceId, serviceId, uuid, "4053544F50");
          } else {
            //发送还打吗命令ACK#
            console.log("继续")
            bluetoothtool.writeBLECharacteristicValue(deviceId, serviceId, uuid, "41434B23");
          }
          wx.navigateTo({
            url: '/pages/contestscore/contestscore'
          });
        }
      });
    });  
  }, 
  setStatuses: function (self, backresult){
    backresult = parseInt(backresult.replace("#", "")).toString(2);
    console.log("获取到的靶位信息：" + backresult);
    let statuses = self.data.statuses; 
    console.log("statuses=" + statuses);   
    for (let i in backresult) {
      let charvalue = backresult.charAt(i);
      if (charvalue == '0') {
        statuses[5-i]=-1;
      } else if (statuses[5-i] == -1){
        statuses[5-i] = 0;
      }
    }
    if ((statuses[0] == -1 && statuses[1] == -1) || 
      (statuses[0] == -1 && statuses[2] == -1)||
      (statuses[1] == -1 && statuses[2] == -1)) {
      statuses[6] = -1;
    } 
    self.setData({ statuses: statuses });
    console.log("statuses=" + statuses);   
  },
  daLei: function (e) {
    httptool.login(function () {
      tabjs.daleiBtnClick();
    });
  },
  myCenter:function(e){
    wx.redirectTo({
      url: '/pages/myCenter/myCenter',
    })
  },
  leiCircle:function(e){
    wx.redirectTo({
      url: '/pages/index/index',
    })
  },
  goToShare:function(e){//去分享
    wx.navigateTo({
      url: '/pages/contestscore/contestscore?shareType='+1,
    })
  },
  closePop:function(e){
    let that=this;
    that.setData({bgCover:true,shareArea:true});
  },
  onReady:function(){
    // 页面渲染完成
  },
  onShow:function(){
    // 页面显示
  },
  onHide:function(){
    // 页面隐藏
  },
  onUnload:function(){
    // 页面关闭
  }
})